package org.makcro.sms.services.chat.web.client.mvc.view;

import org.makcro.sms.services.chat.web.client.AppEvents.BulkEvents;
import org.makcro.sms.services.chat.web.client.widgets.bulk.SendBulkMessageDialog;
import org.makcro.sms.services.chat.web.shared.dto.HistoryItemDto;

import com.extjs.gxt.ui.client.event.EventType;
import com.extjs.gxt.ui.client.mvc.AppEvent;
import com.extjs.gxt.ui.client.mvc.Controller;
import com.extjs.gxt.ui.client.mvc.View;
import com.extjs.gxt.ui.client.widget.Info;

public class SendBulkView extends View {

	private SendBulkMessageDialog	sendBuilkMessageDialog;

	public SendBulkView(Controller controller) {
		super( controller );

		sendBuilkMessageDialog = new SendBulkMessageDialog();
	}

	@Override
	protected void handleEvent(AppEvent event) {
		EventType type = event.getType();
		if (type == BulkEvents.SEND_BULK_REQUESTED) {
			onSendBulkRequested( event );
		}
		else if (type == BulkEvents.BULK_MESSAGES_SENT) {
			onBulkMessgesSent( event );
		}

		else if (type == BulkEvents.BULK_SENDING_FAILED){
			onBulkSendingFailed(event);
		}
	}

	private void onBulkSendingFailed(AppEvent event) {
		Info.display( "Obavestenje", "Slanje bulk poruke nije uspelo" );
		sendBuilkMessageDialog.getButtonBar().enable();
		sendBuilkMessageDialog.hide();
	}

	private void onBulkMessgesSent(AppEvent event) {
		Info.display( "Obavestenje", "Bulk poruka uspesno poslata" );
		sendBuilkMessageDialog.getButtonBar().enable();
		sendBuilkMessageDialog.hide();
	}

	private void onSendBulkRequested(AppEvent event) {
		// extract history item
		HistoryItemDto data = event.<HistoryItemDto> getData();
		// check if initial data is available
		if (data != null) {
			sendBuilkMessageDialog.getReceiverTextField().setValue( data.getFromNumber() );
		}
		else {
			sendBuilkMessageDialog.getReceiverTextField().setValue( "" );
		}

		sendBuilkMessageDialog.show();
	}

}
